package com.smartpro.mis.modular.business.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.smartpro.mis.core.base.controller.BaseController;
import com.smartpro.mis.modular.business.service.IDistributorService;
import com.smartpro.mis.modular.business.service.IUserService;
import com.smartpro.mis.modular.system.model.Distributor;
import com.smartpro.mis.modular.system.model.User;
import com.smartpro.mis.rest.modular.auth.controller.dto.ResponseBean;
import com.smartpro.mis.rest.modular.auth.util.JwtTokenUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpRequest;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
//import com.smartpro.mis.core.log.LogObjectHolder;
import com.smartpro.mis.modular.system.model.Message;
import com.smartpro.mis.modular.business.service.IMessageService;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 消息控制器
 *
 * @author Mengiy
 * @Date 2019-05-07 21:49:20
 */
@RestController
@RequestMapping("/api/service/message")
public class MessageController extends BaseController {


    @Autowired
    private IMessageService messageService;


    @Autowired
    private IUserService userService;

    @Autowired
    private IDistributorService distributorService;


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Map<String, String> dict = ImmutableMap.<String, String>builder()
            .put("0","推广员申请")
            .put("1","推广员申请驳回")
            .put("2","推广员申请审核通过")
              .put("3","推广的商品有购买意向提交")
           .put("4","推广的商品已经退款")
           .put("5","用户购买商品成功")
          .put("6","用户退款成功")
          .put("7","用户团购成功")
          .put("8","用户团购失败")
            .build();
//
//    static {
//        Map megDictory = new HashMap();
//        megDictory.put("0","推广员申请");
//        megDictory.put("1","推广员申请驳回");
//        megDictory.put("2","推广员申请审核通过");
//        megDictory.put("3","推广的商品有购买意向提交");
//        megDictory.put("4","推广的商品已经退款");
//        megDictory.put("5","用户购买商品成功");
//        megDictory.put("6","用户退款成功");
//        megDictory.put("7","用户团购成功");
//        megDictory.put("8","用户团购失败");
//    }

    /**
     * 获取我的消息列表
     */
    @RequestMapping(value = "/getMyMessages",method = RequestMethod.GET)
    @ApiOperation(value = "获取我的消息列表",notes="获取我的全部消息" )
    @ResponseBody
    @RequiresAuthentication
    public Object getMyMessages(HttpServletRequest request) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
        return new ResponseBean(200,"query success",messageService.getMyMessages(user.getUserID(),null,null,0,0));
    }


    /**
     * 根据消息类型查询消息列表
     */
    @RequestMapping(value = "/getMessageListByType",method = RequestMethod.POST)
    @ApiOperation(value = "根据消息类型查询消息列表",notes="条件查询" )
    @ApiImplicitParam(name = "params", value = "格式：messageType:0，备注：消息类型，0：推广员申请;1：推广员申请驳回;2：推广员申请审核通过;3：推广的商品有购买意向提交;" +
            "4：推广的商品已经退款;5：用户购买商品成功;6：用户退款成功;7：用户团购成功;8：用户团购失败", required = true, dataType = "JSONObject")
    @ResponseBody
    @RequiresAuthentication
    public Object getMessageListByType(HttpServletRequest request, @RequestBody JSONObject params) {
        JSONObject result = new JSONObject();
        try {
            if(params.containsKey("messageType")){
                int messageType = params.getInteger("messageType");
                result.put("code",200);
                result.put("message","操作成功");
                result.put("data", messageService.selectMessageByType(messageType,null,null,0,0));
            }else {
                result.put("code",400);
                result.put("message","参数有误");
                result.put("data",params);
            }
        }catch (Exception e){
            result.put("code",400);
            result.put("message",e.getMessage());
            result.put("data",null);
        }
        return result;

    }


    /**
     * 获取全部消息列表
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ApiOperation(value = "获取消息列表",notes="获取全部消息" )
    @ResponseBody
    @RequiresAuthentication
    public Object list() {
        return new ResponseBean(200,"query success",messageService.getMessageList(null,null,0,0));
    }



    /**
     * 条件查询消息列表
     */
    @RequestMapping(value = "/getMessageList",method = RequestMethod.POST)
    @ApiOperation(value = "查询消息列表",notes="条件查询" )
    @ApiImplicitParam(name = "params", value = "json格式查询条件", required = true, dataType = "JSONObject")
    @ResponseBody
    @RequiresAuthentication
    public Object getMessageList(HttpServletRequest request, @RequestBody JSONObject params) {
        JSONObject result = new JSONObject();
//        try {
        Map map = JSONObject.parseObject(params.toJSONString(), Map.class);
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
//        map.put("receiverID",user.getUserID());
            List<Map<String,Object>> rendMegList = new ArrayList<>();
            List<Message> mesList =  messageService.selectByMap(map);
            for(Message m:mesList){
                Map m2 = new HashMap();
                 m2 = JSONObject.parseObject(JSON.toJSONString(m),Map.class);
                 int senderID =  m.getSenderID();
                 int receiverID = m.getReceiverID();
                 String sender = "系统管理员";
                 String receiver = "系统管理员";
                 User user1 = userService.selectById(senderID);
                 User user2 = userService.selectById(receiverID);
                 if(null!=user1)
                     sender= user1.getWechat();
                 if(null!=user2)
                    receiver= user2.getWechat();
                m2.put("sender",sender);
                m2.put("receiver",receiver);
                m2.put("type",dict.get(m.getMessageType()+""));
                 rendMegList.add(m2);
            }
            result.put("code",200);
            result.put("message","操作成功");
            result.put("data",rendMegList);
//        }catch (Exception e){
//            result.put("code",400);
//            result.put("message",e.getMessage());
//            result.put("data",null);
//        }
        return result;

    }


    /**
     * 新增消息
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object add(@RequestBody Message message) {
        messageService.insert(message);
        return SUCCESS_TIP;
    }

    /**
     * 删除消息
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @RequiresAuthentication
    public Object delete(@RequestParam Integer messageId) {
        messageService.deleteById(messageId);
        return SUCCESS_TIP;
    }

    /**
     * 修改消息
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @RequiresAuthentication
    public Object update(Message message) {
        messageService.updateById(message);
        return SUCCESS_TIP;
    }

    /**
     * 获取消息详情
     */
    @ApiOperation(value = "获取消息详情",notes="登录用户通过消息编号获取消息详情" )
    @ApiImplicitParam(name = "messageID", value = "消息编号", required = true, dataType = "Integer")
    @RequestMapping(value = "/getApplyForDistributorMessage/{messageId}",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object getApplyForDistributorMessage(HttpServletRequest request, @PathVariable("messageId") Integer messageId) {
        JSONObject result = new JSONObject();
        Message message = null;
        try {
            message = messageService.selectById(messageId);
//            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//            String authorization = httpServletRequest.getHeader("Authorization");
//            JwtTokenUtil jwt = new JwtTokenUtil();
//            String username = jwt.getUsernameFromToken(authorization);
//            Map<String,Object> condtion = new HashMap();
//            condtion.put("wechat",username);
//            User user = this.userService.selectByMap(condtion).get(0);
            int userID = message.getSenderID();
            User user = this.userService.selectById(userID);
            Distributor distributor = this.distributorService.selectById(userID);
            JSONObject dataRes = new JSONObject();
            dataRes.put("status",distributor.getStatus());
            dataRes.put("messageType",message.getMessageType());
            dataRes.put("userID",userID);
            dataRes.put("belongtoCompany",distributor.getBelongToCompany());
            dataRes.put("childName",user.getChildName());
            dataRes.put("childGender",user.getGender());
            dataRes.put("childBirthday",user.getChildBirthday());
            dataRes.put("mobile",user.getMobile());
            dataRes.put("province",user.getProvince());
            dataRes.put("city",user.getCity());
            dataRes.put("address",user.getAddress());
            dataRes.put("comments",distributor.getApplyForComments());

            //更新消息
            message.setIsRead(0);
            message.setModifyTime(sdf.format(new Date()));
            messageService.updateById(message);

            result.put("code",200);
            result.put("message","操作成功");
            result.put("data", dataRes);
        }catch (Exception e){
            result.put("code",400);
            result.put("message",e.getMessage());
            result.put("data",message);
        }

        return result;
    }
}
